import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import { asyncRoutes } from '@/router' // 动态路由的数组

const bai = ['/404', '/login']
// 前置路由守卫
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  if (store.getters.token) {
    // 存在token
    if (to.path === '/login') {
      // 跳转到主页
      next('/')
      nprogress.done()
    } else {
      if (!store.getters.userId) {
        // 就要调取接口
        const { roles } = await store.dispatch('user/getUserInfo')
        const filterRoutes = asyncRoutes.filter(item => { // 拿到用户能访问的路由
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      }
      next()
    }
  } else {
    if (bai.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
      nprogress.done()
    }
  }
})

// 后置路由守卫
router.afterEach(() => {
  nprogress.done()
})
